Lua keeps all its global variables in a regular table, called the environment. To facilitate such manipulations,
Lua stores the environment itself in a global variable
_G
.
For instance, the following code prints the names of all global variables defined in the current environment:
for _, v in pairs(_G) do print(v) end
And printed outpu is:
--[[
-----------------------------
Printed Output
Global Variables
-----------------------------
[Running] lua "/Users/globalVar.lua"
ipairs
math
os
setmetatable
dofile
_VERSION
error
xpcall
_G -- Notice "_G" is the variable (a table)
-- that was used in the "for" loop
loadstring
type
rawlen
select
rawset
coroutine
require
module
next
arg
debug
bit32
assert
getmetatable
string
pcall
rawequal
load
io
rawget
unpack
print
package
loadfile
collectgarbage
table
tostring
tonumber
pairs
-----------------------------
[Done] exited with code=0 in 0.008 seconds
]]
We can create another global functions, variables and tables and stored in its environment too:
-- create global function and global variable into _G
_G.newFn = function() print("hello world!!!") end
_G.newVar = 3
_G.newFn() -- Printed Output: "hello world!!!"
print(_G.new) -- Printed Output: 3
If instance _G
will appear _G.newFn
and _G.newVar
in the list with all global variable defined previously.
For destroy them simply is necessary to make this:
_G.newFn = nil
_G.new = nil
It's important to indicate this functionality can able deploy lamdba functions, for more details check this trend
Hiya. I'm Ronald, an Industrial Engineer from Colombia. Hope you enjoyed my ad-free, bullshit-free site. If you liked it, tell someone about it.